# 管理员服务
from models import db, Admin
from common.response import APIResponse
import bcrypt

class AdminService:
    @staticmethod
    def get_admin_by_id(admin_id):
        admin = Admin.query.filter_by(id=admin_id).first()
        if not admin:
            return APIResponse.not_found('Admin not found')
        return APIResponse.success(admin.to_dict())

    @staticmethod
    def get_all_admins(args):
        # 分页查询
        page = args.get('page', 1, type=int)
        per_page = args.get('pageSize', 10, type=int)
        # 根据姓名查询
        name = args.get('name')
        if name:
            admins = Admin.query.filter(Admin.name.like(f'%{name}%')).paginate(page=page, per_page=per_page, error_out=False)
        else:
            admins = Admin.query.paginate(page=page, per_page=per_page, error_out=False)
        return APIResponse.success({
            'items': [admin.to_dict() for admin in admins.items],
            'total': admins.total,
            'page': page,
            'per_page': per_page
        })

    @staticmethod
    def create_admin(data):
        # 验证必填字段
        required_fields = ['phone', 'name', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')

        # 检查手机号是否已存在
        if Admin.query.filter_by(phone=data['phone']).first():
            return APIResponse.fail('Phone number already exists', 10002)

        # 密码加密
        password_hash = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())

        # 创建新管理员
        new_admin = Admin(
            phone=data.get('phone'),
            name=data.get('name'),
            head=data.get('head'),
            password=password_hash.decode('utf-8')
        )

        try:
            new_admin.save()
            return APIResponse.success(new_admin.to_dict(), 'Admin created successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def update_admin(admin_id, data):
        admin = Admin.query.filter_by(id=admin_id).first()
        if not admin:
            return APIResponse.not_found('Admin not found')

        # 检查更新的手机号是否已存在
        if 'phone' in data and data['phone'] != admin.phone:
            if Admin.query.filter_by(phone=data['phone']).first():
                return APIResponse.fail('Phone number already exists', 10002)
            admin.phone = data['phone']

        # 更新其他字段
        if 'name' in data:
            admin.name = data['name']
        if 'phone' in data:
            admin.phone = data['phone']
        if 'head' in data:
            admin.head = data['head']
        if 'password' in data and data['password']:
            # 密码加密
            password_hash = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())
            admin.password = password_hash.decode('utf-8')

        try:
            admin.save()
            return APIResponse.success(admin.to_dict(), 'Admin updated successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def delete_admin(admin_id):
        admin = Admin.query.filter_by(id=admin_id).first()
        if not admin:
            return APIResponse.not_found('Admin not found')

        try:
            db.session.delete(admin)
            db.session.commit()
            return APIResponse.success(None, 'Admin deleted successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def admin_login(data):
        # 验证必填字段
        required_fields = ['phone', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')
                
        # 查找管理员
        admin = Admin.query.filter_by(phone=data['phone']).first()
        if not admin:
            return APIResponse.fail('Admin not found', 20001)
        
        # 验证密码
        if not bcrypt.checkpw(data['password'].encode('utf-8'), admin.password.encode('utf-8')):
            return APIResponse.fail('Invalid password', 20002)
        
        return APIResponse.success(admin.to_dict(), 'Login successful')